import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';

import '../log_utils.dart';
import 'EsoImageCacheManager.dart';
import 'image_utils.dart';

/// 图片加载（支持本地与网络图片）
class LoadImage extends StatelessWidget {
  const LoadImage(
    this.image, //网络图片路径
    {
    Key? key,
    //图表宽度
    this.width,
    //图表高度
    this.height,
    //填充模式
    this.fit = BoxFit.cover,
    //图片类型
    this.format = 'png',
    //图片颜色
    this.color,
    //无网络图片的本地占位图片
    this.holderImg = 'assets/images/logo',
  }) : super(key: key);

  final String image;
  final double? width;
  final double? height;
  final BoxFit? fit;
  final String? format;
  final String? holderImg;
  final Color? color;

  @override
  Widget build(BuildContext context) {
    if (image == '' || image == '.' || image == 'null') {
      return LoadAssetImage(
        holderImg!,
        height: height,
        width: width,
        fit: fit,
        color: color,
        format: format,
      );
    } else {
      String imageURL = image;
      if (!image.startsWith('http') && !image.startsWith('https')) {
        imageURL = ImageUtils.AppImagePath(image);
      }
      return CachedNetworkImage(
        imageUrl: imageURL,
        placeholder: (context, url) => LoadAssetImage(holderImg!,
            height: height, width: width, fit: fit, color: color),
        errorWidget: (context, url, error) => LoadAssetImage(
          holderImg!,
          height: height,
          width: width,
          fit: fit,
          color: color,
        ),
        width: width,
        height: height,
        fit: fit,
        color: color,
        cacheManager: EsoImageCacheManager(),
      );
    }
  }
}

/// 加载本地资源图片
class LoadAssetImage extends StatelessWidget {
  const LoadAssetImage(
    this.image, {
    Key? key,
    this.width,
    this.height,
    this.cacheWidth,
    this.cacheHeight,
    this.fit,
    this.format = 'png',
    this.color,
  }) : super(key: key);

  final String image;
  final double? width;
  final double? height;
  final int? cacheWidth;
  final int? cacheHeight;
  final BoxFit? fit;
  final String? format;
  final Color? color;

  @override
  Widget build(BuildContext context) {
    return Image.asset(
      ImageUtils.getImgPath(image, format: format),
      height: height,
      width: width,
      cacheWidth: cacheWidth,
      cacheHeight: cacheHeight,
      fit: fit,
      color: color,

      /// 忽略图片语义
      excludeFromSemantics: true,
    );
  }
}
